/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.ui.activities.adapters;

import java.util.List;

import utsc.apps.utschedule.R;
import utsc.apps.utschedule.classes.Timetable;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

/**
 * A simple list adapter to show a list of {@link Timetable archive timetables}. 
 *
 */
public class TimetableAdapter extends ArrayAdapter<Timetable> {

	private static final String GPA_LB_TEXT="GPA: ";
	
	public TimetableAdapter(Context context, int textViewResourceId,
			List<Timetable> objects) {
		super(context, textViewResourceId, objects);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		//first inflate our view and cache the ui elements into its viewholder object
		if (convertView==null) {
			holder=new ViewHolder();
			convertView=LayoutInflater.from(getContext()).inflate(R.layout.gpa_list_item, null);
			holder._txtName=(TextView) convertView.findViewById(R.id.txt_list_title);
			holder._txtGpa=(TextView) convertView.findViewById(R.id.txt_list_gpa);
			convertView.setTag(holder);
		}else {
			//always retrieve the viewholder from the tag
			holder=(ViewHolder) convertView.getTag();
		}
		Timetable timetable=getItem(position);
		if (timetable!=null) {
			holder._txtName.setText(timetable.get_title());
			String gpaOut = String.valueOf(timetable.get_gpaCalculator().get_GPA());
			if (gpaOut.length() > 4)
				gpaOut = gpaOut.substring(0, 4);				
			else if (gpaOut.length() < 4)
				gpaOut += "0";
			holder._txtGpa.setText(GPA_LB_TEXT+gpaOut);
		}else {
			holder._txtName.setText("");
		}
		
		return convertView;
	}
	
	private static class ViewHolder{
		TextView _txtName;
		TextView _txtGpa;
	}
}
